package org.jeecg.modules.solitaire_app.app.controller;

import java.util.*;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageInfo;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.solitaire_app.app.entity.VO.YsyDrivingTrackNodeVO;
import org.jeecg.modules.solitaire_app.app.entity.VO.YsyDrivingTrackVO;
import org.jeecg.modules.solitaire_app.app.entity.YsyDrivingTrack;
import org.jeecg.modules.solitaire_app.app.entity.YsySystemContent;
import org.jeecg.modules.solitaire_app.app.entity.YsyUsers;
import org.jeecg.modules.solitaire_app.app.service.IYsyDrivingTrackService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.solitaire_app.app.service.IYsySystemContentService;
import org.jeecg.modules.solitaire_app.app.service.IYsyUsersService;
import org.jeecg.modules.solitaire_app.utils.LocationUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * @Description: 车辆轨迹订单
 * @Author: jeecg-boot
 * @Date: 2023-11-30
 * @Version: V1.0
 */
@Slf4j
@Api(tags = "车辆轨迹订单")
@RestController
@RequestMapping("/app/ysyDrivingTrack")
public class YsyDrivingTrackController extends JeecgController<YsyDrivingTrack, IYsyDrivingTrackService> {
    @Autowired
    private IYsyDrivingTrackService ysyDrivingTrackService;
    @Autowired
    private IYsyUsersService ysyUsersService;
    @Autowired
    private IYsySystemContentService iYsySystemContentService;
    @Value("${tengcent.apiMap}")
    private String apiMap;

    /**
     * 分页列表查询
     *
     * @param ysyDrivingTrack
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "车辆轨迹订单-分页列表查询")
    @ApiOperation(value = "车辆轨迹订单-分页列表查询", notes = "车辆轨迹订单-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(YsyDrivingTrack ysyDrivingTrack,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {

//        QueryWrapper<YsyDrivingTrack> queryWrapper = QueryGenerator.initQueryWrapper(ysyDrivingTrack, req.getParameterMap());
//        queryWrapper.orderByDesc("create_time");
        LambdaUpdateWrapper<YsyDrivingTrack>
                queryWrapper = new LambdaUpdateWrapper<>();
        queryWrapper.orderByDesc(YsyDrivingTrack::getCreateTime);
        if (ObjectUtil.isNotEmpty(ysyDrivingTrack.getStatus())) {
            queryWrapper.eq(YsyDrivingTrack::getStatus, ysyDrivingTrack.getStatus());
        }
        if (ObjectUtil.isNotEmpty(ysyDrivingTrack.getUserId())) {
            queryWrapper.eq(YsyDrivingTrack::getUserId, ysyDrivingTrack.getUserId());
        }

        if (ObjectUtil.isNotEmpty(ysyDrivingTrack.getZhdAddress())) {
            queryWrapper.like(true, YsyDrivingTrack::getZhdAddress, ysyDrivingTrack.getZhdAddress());
        }

        if (ObjectUtil.isNotEmpty(ysyDrivingTrack.getRealName())) {
            YsyUsers ysyUsersObj = ysyUsersService.getOne(Wrappers.<YsyUsers>lambdaQuery()
                    .eq(YsyUsers::getRealName, ysyDrivingTrack.getRealName())
                    .eq(YsyUsers::getSource, 1));
            queryWrapper.eq(YsyDrivingTrack::getUserId, ysyUsersObj.getId());
        }

        Page<YsyDrivingTrack> page = new Page<YsyDrivingTrack>(pageNo, pageSize);
        IPage<YsyDrivingTrack> pageList = ysyDrivingTrackService.page(page, queryWrapper);
        pageList.getRecords().forEach(item -> {
            YsyUsers ysyUsers = ysyUsersService.getById(item.getUserId());
            item.setPhone(ysyUsers.getPhone());
            item.setUserName(ysyUsers.getNickName());
            item.setRealName(ysyUsers.getRealName());
        });
        return Result.ok(pageList);
    }

    /**
     * 分页列表查询
     *
     * @param ysyDrivingTrack
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "车辆轨迹订单-数据大屏")
    @ApiOperation(value = "车辆轨迹订单-数据大屏", notes = "车辆轨迹订单-数据大屏")
    @PostMapping(value = "/getBigDataDrivingTracks")
    public Result<PageInfo<YsyDrivingTrack>> getBigDataDrivingTracks(@RequestBody Map<String,Object> map){
        return ysyDrivingTrackService.getBigDataDrivingTracks(map);
    }

    /**
     * 大屏获取全部订单数量
     *
     * @return
     */
    @AutoLog(value = "车辆轨迹订单-大屏获取全部订单数量")
    @ApiOperation(value = "车辆轨迹订单-大屏获取全部订单数量", notes = "车辆轨迹订单-大屏获取全部订单数量")
    @GetMapping(value = "/getBigDataAllOrders")
    public Result<Integer> getBigDataAllOrders(){
        return ysyDrivingTrackService.getBigDataAllOrders();
    }

    /**
     * 添加
     *
     * @param ysyDrivingTrack
     * @return
     */
    @AutoLog(value = "车辆轨迹订单-添加")
    @ApiOperation(value = "车辆轨迹订单-添加", notes = "车辆轨迹订单-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody YsyDrivingTrack ysyDrivingTrack) {

        YsyUsers ysyUsers = ysyUsersService.getById(ysyDrivingTrack.getUserId());

        ysyDrivingTrack.setServiceNo(1);

        if (ysyUsers.getDrivingTrackNum() <= 0) {
            return Result.error("车辆轨迹次数不足！！！");
        }
        // 设置起始时间为当前时间减去72小时
        Date startTime = new Date(System.currentTimeMillis() - (1000 * 60 * 60 * 72));
        // 将起始时间作为查询条件之一
//        List<YsyDrivingTrack> ysyDrivingTracks = ysyDrivingTrackService.getYsyDrivingTrackTime(startTime, new Date()
//                , ysyDrivingTrack.getCarNo());
//
//        if (ysyDrivingTracks.size() > 0) {
//            return Result.error("已有进行中订单，请勿重复下单！！！");
//        }

        //下单默认-待付款,走编辑接口修改付款状态
        ysyDrivingTrack.setStatus(1);
        ysyDrivingTrackService.save(ysyDrivingTrack);

        return Result.ok(ysyDrivingTrack.getId());
    }

    /**
     * 编辑
     *
     * @param ysyDrivingTrack
     * @return
     */
    @AutoLog(value = "车辆轨迹订单-编辑")
    @ApiOperation(value = "车辆轨迹订单-编辑", notes = "车辆轨迹订单-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody YsyDrivingTrack ysyDrivingTrack) {
        try {
            //新增第三方平台下单
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("sendAddress", ysyDrivingTrack.getZhdAddress());
            jsonObject.put("sendDetailAddress", getAddress(ysyDrivingTrack.getZhdAddress()));
            jsonObject.put("sendCompany", ysyDrivingTrack.getZhdAddress());
            jsonObject.put("consigNo", ysyDrivingTrack.getId());
            JSONObject obj1 = new JSONObject();
            obj1.put("deviceType", 1);
            obj1.put("vehicleNo", ysyDrivingTrack.getCarNo());
            jsonObject.put("gentlyBillVehicle", obj1);
            JSONObject obj2 = new JSONObject();
            obj2.put("goodsName", ysyDrivingTrack.getOilNo() + ysyDrivingTrack.getOilType());
            obj2.put("weight", 33);
            obj2.put("unit", "吨");
            jsonObject.put("gentlyBillGoods", obj2);
            jsonObject.put("recvCompany", ysyDrivingTrack.getXhdAddress());
            jsonObject.put("recvAddress", ysyDrivingTrack.getXhdAddress());
            jsonObject.put("recvDetailAddress", getAddress(ysyDrivingTrack.getXhdAddress()));
            jsonObject.put("licensePlateColor", 2);

            String token = getToken();
            //先查询第三方具体的订单
            String billListUrl = "https://gw.66yunlian.cn/gently-bill-core/standardWayBill/saveAndUpdate";

            String trackResJson = HttpRequest.post(billListUrl)
                    .header("Token", token)
                    .header("Content-Type", "application/json")
                    .body(jsonObject.toString()).execute().body();

            if (JSONObject.parseObject(trackResJson).getInteger("code") == 104) {
                //token失效了
                return Result.error("token过期，请联系客服");
            }

            ysyDrivingTrackService.updateById(ysyDrivingTrack);

            YsyUsers ysyUsers = ysyUsersService.getById(ysyDrivingTrack.getUserId());
            //减少次数
            ysyUsers.setDrivingTrackNum(ysyUsers.getDrivingTrackNum() - 1);

            ysyUsersService.updateById(ysyUsers);

            return Result.ok("编辑成功!");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error("服务器响应失败");
        }
    }

    public List<String> getAddress(String addrssName) {
        String url = "https://apis.map.qq.com/ws/geocoder/v1/?address=" + addrssName + "&key=" + this.apiMap;
        String jsonStr = HttpUtil.get(url);
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        if (jsonObject.getInteger("status") == 0) {
            JSONObject json = jsonObject.getJSONObject("result").getJSONObject("address_components");
            List<String> strings = new ArrayList<>();
            strings.add(json.getString("province"));
            strings.add(json.getString("city"));
            strings.add(json.getString("district"));
            return strings;
        } else {
            return null;
        }
    }

    public String getAddressName(double lat, double lng) {
        String url = "https://apis.map.qq.com/ws/geocoder/v1/?location=" + lat + "," + lng + "&key=" + this.apiMap;
        String jsonStr = HttpUtil.get(url);
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        if (jsonObject.getInteger("status") == 0) {
            JSONObject json = jsonObject.getJSONObject("result").getJSONObject("formatted_addresses");
            return json.getString("standard_address") + json.getString("recommend");
        } else {
            return null;
        }
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "车辆轨迹订单-通过id删除")
    @ApiOperation(value = "车辆轨迹订单-通过id删除", notes = "车辆轨迹订单-通过id删除")
    @GetMapping(value = "/delete/{id}")
    public Result<?> delete(@PathVariable("id") String id) {
        ysyDrivingTrackService.removeById(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "车辆轨迹订单-批量删除")
    @ApiOperation(value = "车辆轨迹订单-批量删除", notes = "车辆轨迹订单-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.ysyDrivingTrackService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "车辆轨迹订单-通过id查询")
    @ApiOperation(value = "车辆轨迹订单-通过id查询", notes = "车辆轨迹订单-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        YsyDrivingTrack ysyDrivingTrack = ysyDrivingTrackService.getById(id);

        YsyUsers ysyUsers = ysyUsersService.getById(ysyDrivingTrack.getUserId());
        ysyDrivingTrack.setDrivingTrackNo(ysyUsers.getDrivingTrackNum());
        ysyDrivingTrack.setUserName(ObjectUtil.isNotEmpty(ysyUsers.getRealName()) ? ysyUsers.getRealName() : ysyUsers.getNickName());
        return Result.ok(ysyDrivingTrack);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param ysyDrivingTrack
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, YsyDrivingTrack ysyDrivingTrack) {
        return super.exportXls(request, ysyDrivingTrack, YsyDrivingTrack.class, "车辆轨迹订单");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, YsyDrivingTrack.class);
    }

    /**
     * 查询轨迹详情
     *
     * @param orderId
     * @return
     */
    @AutoLog(value = "车辆轨迹订单-查询轨迹详情")
    @ApiOperation(value = "车辆轨迹订单-查询轨迹详情", notes = "车辆轨迹订单-查询轨迹详情")
    @GetMapping("/getYsyDrivingTrackVO/{orderId}")
    public Result<YsyDrivingTrackVO> getYsyDrivingTrackVO(@PathVariable("orderId") String orderId) {

        Result<YsyDrivingTrackVO> result = new Result<>();

        try {
            String token = getToken();
            //先查询第三方具体的订单
            String billListUrl = "https://gw.66yunlian.cn/gently-bill-core/standardWayBill/billList";
            JSONObject billListJson = new JSONObject();
            billListJson.put("consigNo", orderId);
            String resJson = HttpRequest.post(billListUrl)
                    .header("Token", token)
                    .header("Content-Type", "application/json")
                    .body(billListJson.toString()).execute().body();

            if (JSONObject.parseObject(resJson).getInteger("code") == 104) {
                //token失效了
                result.setMessage("token过期，请联系客服");
                result.setCode(500);
                result.setSuccess(false);
                return result;
            }

            YsyDrivingTrack ysyDrivingTrack = ysyDrivingTrackService.getOne(Wrappers.<YsyDrivingTrack>lambdaQuery()
                    .eq(YsyDrivingTrack::getId, orderId));

            if (ObjectUtil.isEmpty(ysyDrivingTrack)) {
                result.setMessage("未查询到该订单！！！");
                result.setCode(500);
                result.setSuccess(false);
                return result;
            }

            JSONArray arrResJson = JSONObject.parseObject(resJson)
                    .getJSONObject("data")
                    .getJSONArray("list");

            // 半个小时后还没查到返回次数
            Date startTime = new Date(ysyDrivingTrack.getCreateTime().getTime() + (1000 * 60 * 30 * 1));

            if (arrResJson.size() == 0 && new Date().before(startTime)) {
                result.setMessage("轨迹生成中，请稍等片刻\n" +
                        "（20分钟后仍无法查询，请检查司机GPS）");
                result.setCode(500);
                result.setSuccess(false);
                return result;
            }

            if (ysyDrivingTrack.getStatus() == 2 && new Date().after(startTime) && ObjectUtil.isEmpty(arrResJson)) {
                //返回次数
                YsyUsers ysyUsers = ysyUsersService.getById(ysyDrivingTrack.getUserId());
                ysyUsers.setDrivingTrackNum(ysyUsers.getDrivingTrackNum() + 1);
                ysyUsersService.updateById(ysyUsers);

                ysyDrivingTrack.setStatus(3);
                //修改订单的返回次数标记
                ysyDrivingTrackService.updateById(ysyDrivingTrack);

                result.setMessage("GPS同步失败，请联系承运商，本次订单不扣轨迹次数");
                result.setCode(500);
                result.setSuccess(false);
                return result;
            }

            String billId = JSONObject.parseObject(resJson)
                    .getJSONObject("data")
                    .getJSONArray("list")
                    .getJSONObject(0)
                    .getString("billId");

            JSONObject trackJson = new JSONObject();
            trackJson.put("billId", billId);
            String trackUrl = "https://gw.66yunlian.cn/gently-bill-core/standardMonitorCenter/queryGnetlyBillTrack";
            String trackResJson = HttpRequest.post(trackUrl)
                    .header("Token", token)
                    .header("Content-Type", "application/json")
                    .body(trackJson.toString()).execute().body();

            if (JSONObject.parseObject(trackResJson).getInteger("code") == 104) {
                //token失效了
                result.setMessage("token过期，请联系客服");
                result.setCode(500);
                result.setSuccess(false);
                return result;
            }

            JSONObject trackJSON = JSONObject.parseObject(trackResJson).getJSONObject("data");
            if (ObjectUtil.isEmpty(trackJSON.getJSONObject("trackList"))) {
                result.setMessage("轨迹生成中，请稍等片刻\n" +
                        "（20分钟后仍无法查询，请检查司机GPS）");
                result.setCode(500);
                result.setSuccess(false);
                return result;
            }
            JSONArray jsonArray = trackJSON.getJSONObject("trackList").getJSONArray("position");
            // 半个小时后还没查到返回次数
            if (ysyDrivingTrack.getStatus() == 2 && new Date().after(startTime) && ObjectUtil.isEmpty(jsonArray)) {
                //返回次数
                YsyUsers ysyUsers = ysyUsersService.getById(ysyDrivingTrack.getUserId());
                ysyUsers.setDrivingTrackNum(ysyUsers.getDrivingTrackNum() + 1);
                ysyUsersService.updateById(ysyUsers);

                ysyDrivingTrack.setStatus(3);
                //修改订单的返回次数标记
                ysyDrivingTrackService.updateById(ysyDrivingTrack);

                result.setMessage("GPS同步失败，请联系承运商，本次订单不扣轨迹次数");
                result.setCode(500);
                result.setSuccess(false);
                return result;
            }
            //轨迹订单已经返回
            if (ysyDrivingTrack.getStatus() == 3 && ObjectUtil.isEmpty(jsonArray)) {
                result.setMessage("本次订单已取消，轨迹次数已返还，若有疑问请联系客服");
                result.setCode(500);
                result.setSuccess(false);
                return result;
            }
            if (ObjectUtil.isEmpty(jsonArray)) {
                result.setMessage("轨迹生成中，请稍等片刻\n" +
                        "（20分钟后仍无法查询，请检查司机GPS）");
                result.setCode(500);
                result.setSuccess(false);
                return result;
            }
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject locationObj = jsonArray.getJSONObject(i);
                double[] map = LocationUtil.calWGS84toGCJ02(locationObj.getDouble("latitude"), locationObj.getDouble("longitude"));
                locationObj.put("latitude", map[0]);
                locationObj.put("longitude", map[1]);
            }

            JSONObject trackListObj = trackJSON.getJSONObject("trackList");
            if (ObjectUtil.isNotEmpty(trackListObj)) {
                if (ObjectUtil.isNotEmpty(trackListObj.getDouble("endLatitude")) && ObjectUtil.isNotEmpty(trackListObj.getDouble("endLongitude"))) {
                    double[] trackEndMap = LocationUtil.calWGS84toGCJ02(trackListObj.getDouble("endLatitude"), trackListObj.getDouble("endLongitude"));
                    trackListObj.put("endLatitude", trackEndMap[0]);
                    trackListObj.put("endLongitude", trackEndMap[1]);
                }

                if (ObjectUtil.isNotEmpty(trackListObj.getDouble("startLatitude")) && ObjectUtil.isNotEmpty(trackListObj.getDouble("startLongitude"))) {
                    double[] trackStartMap = LocationUtil.calWGS84toGCJ02(trackListObj.getDouble("startLatitude"), trackListObj.getDouble("startLongitude"));
                    trackListObj.put("startLatitude", trackStartMap[0]);
                    trackListObj.put("startLongitude", trackStartMap[1]);
                }
            }

            JSONArray tarJson = trackJSON.getJSONArray("targetPoints");
            for (int i = 0; i < tarJson.size(); i++) {
                JSONObject tarJsonObj = tarJson.getJSONObject(i);
                double[] map = LocationUtil.calWGS84toGCJ02(tarJsonObj.getDouble("lat"), tarJsonObj.getDouble("lon"));
                tarJsonObj.put("lat", map[0]);
                tarJsonObj.put("lon", map[1]);
            }

            JSONObject jsonObject = trackJSON.getJSONObject("gpsLocation");
            double[] mapGps = {};
            if (ObjectUtil.isNotEmpty(jsonObject)) {
                mapGps = LocationUtil.calWGS84toGCJ02(jsonObject.getDouble("latitude"), jsonObject.getDouble("longitude"));
                jsonObject.put("latitude", mapGps[0]);
                jsonObject.put("longitude", mapGps[1]);
            }

            JSONObject recvAddressInfoObj = trackJSON.getJSONObject("recvAddressInfo");
            double[] recvAddressInfoMap = {};
            if (ObjectUtil.isNotEmpty(recvAddressInfoObj)) {
                recvAddressInfoMap = LocationUtil.calWGS84toGCJ02(recvAddressInfoObj.getDouble("addressLat"), recvAddressInfoObj.getDouble("addressLon"));
                recvAddressInfoObj.put("addressLat", recvAddressInfoMap[0]);
                recvAddressInfoObj.put("addressLon", recvAddressInfoMap[1]);
            }

            JSONObject sendAddressInfoObj = trackJSON.getJSONObject("sendAddressInfo");
            double[] sendAddressInfoMap = {};
            if (ObjectUtil.isNotEmpty(recvAddressInfoObj)) {
                sendAddressInfoMap = LocationUtil.calWGS84toGCJ02(sendAddressInfoObj.getDouble("addressLat"), sendAddressInfoObj.getDouble("addressLon"));
                sendAddressInfoObj.put("addressLat", sendAddressInfoMap[0]);
                sendAddressInfoObj.put("addressLon", sendAddressInfoMap[1]);
            }

            String totalMileage = "0km";
            if (ObjectUtil.isNotEmpty(trackJSON.getJSONObject("trackList").getDouble("endMileage")) && ObjectUtil.isNotEmpty(trackJSON.getJSONObject("trackList").getDouble("startMileage"))) {
                totalMileage = ((trackJSON.getJSONObject("trackList").getDouble("endMileage") - trackJSON.getJSONObject("trackList").getDouble("startMileage"))) + "km";
            }
            YsyDrivingTrackVO ysyDrivingTrackVO = YsyDrivingTrackVO.builder()
                    .vehicleNo(trackJSON.getString("vehicleNo"))
                    .trackEndTime(trackJSON.getString("trackEndTime"))
                    .trackStartTime(trackJSON.getString("trackStartTime"))
                    .trackDuration(trackJSON.getString("trackDuration"))
                    .gpsLocation(ObjectUtil.isNotEmpty(trackJSON.getJSONObject("gpsLocation")) ? trackJSON.getJSONObject("gpsLocation").toJSONString() : null)
                    .currentAddress(mapGps.length > 0 ? getAddressName(mapGps[0], mapGps[1]) : null)
                    .trackList(trackJSON.getJSONObject("trackList").toJSONString())
                    .recvAddressInfo(trackJSON.getJSONObject("recvAddressInfo").toJSONString())
                    .sendAddressInfo(trackJSON.getJSONObject("sendAddressInfo").toJSONString())
                    .targetPoints(trackJSON.getJSONArray("targetPoints").toJSONString())
                    .totalMileage(totalMileage)
                    .estimatedArrivalTime(trackJSON.getString("estimatedArrivalTime"))
                    .remainingMileage(trackJSON.getDouble("remainingMileage") == 0 ? "" : String.format("%.2f", trackJSON.getDouble("remainingMileage") / 1000) + "km")
                    .build();

            JSONObject recvAddressObj = JSONObject.parseObject(ysyDrivingTrackVO.getRecvAddressInfo());
            if (ObjectUtil.isNotEmpty(recvAddressObj)) {
                double[] recvMap = LocationUtil.calWGS84toGCJ02(recvAddressObj.getDouble("addressLat"), recvAddressObj.getDouble("addressLon"));
                recvAddressObj.put("addressLat", recvMap[0]);
                recvAddressObj.put("addressLon", recvMap[1]);
            }

            JSONObject sendAddressObj = JSONObject.parseObject(ysyDrivingTrackVO.getSendAddressInfo());
            if (ObjectUtil.isNotEmpty(sendAddressObj)) {
                double[] sendMap = LocationUtil.calWGS84toGCJ02(sendAddressObj.getDouble("addressLat"), sendAddressObj.getDouble("addressLon"));
                sendAddressObj.put("addressLat", sendMap[0]);
                sendAddressObj.put("addressLon", sendMap[1]);
            }

            JSONObject trackObj = JSONObject.parseObject(ysyDrivingTrackVO.getTrackList());
            if (ObjectUtil.isNotEmpty(trackObj)) {
                if (ObjectUtil.isNotEmpty(trackObj.getDouble("endLatitude")) && ObjectUtil.isNotEmpty(trackObj.getDouble("endLongitude"))) {
                    double[] trackEndMap = LocationUtil.calWGS84toGCJ02(trackObj.getDouble("endLatitude"), trackObj.getDouble("endLongitude"));
                    trackObj.put("endLatitude", trackEndMap[0]);
                    trackObj.put("endLongitude", trackEndMap[1]);
                    ysyDrivingTrackVO.setEndAddressName(getAddressName(trackEndMap[0], trackEndMap[1]));
                }

                if (ObjectUtil.isNotEmpty(trackObj.getDouble("startLatitude")) && ObjectUtil.isNotEmpty(trackObj.getDouble("startLongitude"))) {
                    double[] trackStartMap = LocationUtil.calWGS84toGCJ02(trackObj.getDouble("startLatitude"), trackObj.getDouble("startLongitude"));
                    trackObj.put("startLatitude", trackStartMap[0]);
                    trackObj.put("startLongitude", trackStartMap[1]);
                    ysyDrivingTrackVO.setStartAddressName(getAddressName(trackStartMap[0], trackStartMap[1]));
                }
            }

            ysyDrivingTrackVO.setTrackList(trackObj.toJSONString());

//            ysyDrivingTrack.setStatus(4);
//            //修改订单的查询成功
//            ysyDrivingTrackService.updateById(ysyDrivingTrack);

            result.setCode(200);
            result.setSuccess(true);
            result.setResult(ysyDrivingTrackVO);
            return result;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.setMessage("轨迹生成中，请稍等片刻\n" +
                    "（20分钟后仍无法查询，请检查司机GPS）");
            result.setCode(500);
            result.setSuccess(false);
            return result;
        }
    }

    /**
     * 查询轨迹事件
     *
     * @param orderId
     * @return
     */
    @AutoLog(value = "车辆轨迹订单-查询轨迹事件")
    @ApiOperation(value = "车辆轨迹订单-查询轨迹事件", notes = "车辆轨迹订单-查询轨迹事件")
    @GetMapping("/YsyDrivingTrackNodeVO/{orderId}")
    public Result<YsyDrivingTrackNodeVO> YsyDrivingTrackNodeVO(@PathVariable("orderId") String orderId) {

        Result<YsyDrivingTrackNodeVO> result = new Result<>();

        try {
            String token = getToken();
            //先查询第三方具体的订单
            String billListUrl = "https://gw.66yunlian.cn/gently-bill-core/standardWayBill/billList";
            JSONObject billListJson = new JSONObject();
            billListJson.put("consigNo", orderId);
            String resJson = HttpRequest.post(billListUrl)
                    .header("Token", token)
                    .header("Content-Type", "application/json")
                    .body(billListJson.toString()).execute().body();

            if (JSONObject.parseObject(resJson).getInteger("code") == 104) {
                //token失效了
                result.setMessage("token过期，请联系客服");
                result.setCode(500);
                result.setSuccess(false);
                return result;
            }

            JSONArray arrResJson = JSONObject.parseObject(resJson)
                    .getJSONObject("data")
                    .getJSONArray("list");
            if (arrResJson.size() == 0) {
                result.setMessage("未查询到该订单");
                result.setCode(500);
                result.setSuccess(false);
                return result;
            }
            String billId = JSONObject.parseObject(resJson)
                    .getJSONObject("data")
                    .getJSONArray("list")
                    .getJSONObject(0)
                    .getString("billId");

            JSONObject trackJson = new JSONObject();
            trackJson.put("billId", billId);
            trackJson.put("source", 1);
            String trackUrl = "https://gw.66yunlian.cn/gently-bill-core/standardMonitorCenter/queryGnetlyBillNode";
            String trackResJson = HttpRequest.post(trackUrl)
                    .header("Token", token)
                    .header("Content-Type", "application/json")
                    .body(trackJson.toString()).execute().body();

            if (JSONObject.parseObject(resJson).getInteger("code") == 104) {
                //token失效了
                result.setMessage("token过期，请联系客服");
                result.setCode(500);
                result.setSuccess(false);
                return result;
            }

            JSONObject trackJSON = JSONObject.parseObject(trackResJson).getJSONObject("data");

            YsyDrivingTrackNodeVO ysyDrivingTrackVO = YsyDrivingTrackNodeVO.builder()
                    .alarmLogs(trackJSON.getJSONArray("alarmLogs").toJSONString())
                    .progressLogs(trackJSON.getJSONArray("progressLogs").toJSONString())
                    .build();

            result.setCode(200);
            result.setSuccess(true);
            result.setResult(ysyDrivingTrackVO);
            return result;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.setMessage("轨迹生成中，请稍等片刻\n" +
                    "（20分钟后仍无法查询，请检查司机GPS）");
            result.setCode(500);
            result.setSuccess(false);
            return result;
        }
    }

    public String getToken() {
        YsySystemContent ysySystemContent = iYsySystemContentService.getOneData(12);
        String tokens = ysySystemContent.getContent();
        String token = tokens.split("<p>--|--</p>")[1];
        return token;
    }

    public static void main(String[] args) {
        String url = "https://apis.map.qq.com/ws/geocoder/v1/?address=河南省郑州市管城回族区商城路与管城街交叉口向东30米路南(商城路252号附8号" + "&key=VBMBZ-5P4RW-QMURT-YAZXR-BVRE7-VHBN7";
        String jsonStr = HttpUtil.get(url);
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        if (jsonObject.getInteger("status") == 0) {
            JSONObject json = jsonObject.getJSONObject("result");
            System.out.println(json);
        }
    }
}
